import { createStore } from 'vuex'
import api from '../utils/api'

export default createStore({
  state: {
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('token') || null,
    userType: localStorage.getItem('userType') || null,
    conversations: [],
    currentConversation: null,
    messages: [],
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
      if (user) {
        localStorage.setItem('user', JSON.stringify(user))
      } else {
        localStorage.removeItem('user')
      }
    },
    SET_TOKEN(state, token) {
      state.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    SET_USER_TYPE(state, userType) {
      state.userType = userType
      if (userType) {
        localStorage.setItem('userType', userType)
      } else {
        localStorage.removeItem('userType')
      }
    },
    SET_CONVERSATIONS(state, conversations) {
      state.conversations = conversations
    },
    SET_CURRENT_CONVERSATION(state, conversation) {
      state.currentConversation = conversation
    },
    SET_MESSAGES(state, messages) {
      state.messages = messages
    },
    ADD_MESSAGE(state, message) {
      state.messages.push(message)
    },
    UPDATE_MESSAGE(state, { index, content }) {
      if (state.messages[index]) {
        // 直接更新内容
        state.messages[index].content = content
        // 强制触发响应式更新 - 创建新数组引用
        state.messages = [...state.messages]
        console.log(
          '消息已更新，索引:',
          index,
          '新内容:',
          content,
          '消息数组长度:',
          state.messages.length
        )
      }
    },
    UPDATE_MESSAGE_BY_ID(state, { messageId, content }) {
      const messageIndex = state.messages.findIndex((msg) => msg.id === messageId)
      if (messageIndex !== -1) {
        // 更新消息内容
        state.messages[messageIndex].content = content
        // 强制触发响应式更新 - 创建新数组引用
        state.messages = [...state.messages]
        // console.log(
        //   '消息已通过ID更新，ID:',
        //   messageId,
        //   '索引:',
        //   messageIndex,
        //   '新内容:',
        //   content,
        //   '消息数组长度:',
        //   state.messages.length
        // )
      } else {
        console.warn('未找到指定ID的消息:', messageId)
      }
    },
    ADD_CONVERSATION(state, conversation) {
      state.conversations.unshift(conversation)
    },
    REMOVE_CONVERSATION(state, conversationId) {
      state.conversations = state.conversations.filter((c) => c.id !== conversationId)
    },
    UPDATE_CONVERSATION_TITLE(state, { conversationId, title }) {
      // 更新对话列表中的标题
      const conversation = state.conversations.find((c) => c.id === conversationId)
      if (conversation) {
        conversation.title = title
        // 强制触发响应式更新
        state.conversations = [...state.conversations]
      }

      // 如果当前对话是更新的对话，也更新当前对话
      if (state.currentConversation && state.currentConversation.id === conversationId) {
        state.currentConversation.title = title
        // 强制触发响应式更新
        state.currentConversation = { ...state.currentConversation }
      }

      console.log('对话标题已更新:', { conversationId, title })
    },
  },
  actions: {
    // 初始化用户数据（页面刷新时调用）
    async initUserData({ commit, state }) {
      const token = localStorage.getItem('token')
      const userType = localStorage.getItem('userType')
      const user = JSON.parse(localStorage.getItem('user') || 'null')

      if (token && userType && user) {
        // 直接从 localStorage 恢复用户数据
        commit('SET_TOKEN', token)
        commit('SET_USER_TYPE', userType)
        commit('SET_USER', user)
      }
    },

    async login({ commit }, credentials) {
      try {
        const response = await api.post('/auth/login', credentials)
        const { token, username, nickname, email } = response.data

        commit('SET_TOKEN', token)
        commit('SET_USER_TYPE', 'user')
        commit('SET_USER', { username, nickname, email })

        return response
      } catch (error) {
        throw error
      }
    },
    async adminLogin({ commit }, credentials) {
      try {
        const response = await api.post('/admin/auth/login', credentials)
        const { token, username, nickname, email } = response.data

        commit('SET_TOKEN', token)
        commit('SET_USER_TYPE', 'admin')
        commit('SET_USER', { username, nickname, email })

        return response
      } catch (error) {
        throw error
      }
    },
    async register({ commit }, userData) {
      try {
        const response = await api.post('/auth/register', userData)
        return response
      } catch (error) {
        throw error
      }
    },
    logout({ commit }) {
      commit('SET_TOKEN', null)
      commit('SET_USER_TYPE', null)
      commit('SET_USER', null)
      commit('SET_CONVERSATIONS', [])
      commit('SET_CURRENT_CONVERSATION', null)
      commit('SET_MESSAGES', [])
    },
    async fetchConversations({ commit }) {
      try {
        const response = await api.get('/chat/conversations')
        commit('SET_CONVERSATIONS', response.data)
        return response
      } catch (error) {
        throw error
      }
    },
    async createConversation({ commit }, title) {
      try {
        const response = await api.post('/chat/conversations', null, {
          params: { title },
        })
        commit('ADD_CONVERSATION', response.data)
        return response
      } catch (error) {
        throw error
      }
    },
    async fetchConversationMessages({ commit }, conversationId) {
      try {
        const response = await api.get(`/chat/conversations/${conversationId}`)
        commit('SET_CURRENT_CONVERSATION', response.data)
        commit('SET_MESSAGES', response.data.messages || [])
        return response
      } catch (error) {
        throw error
      }
    },
    async updateConversationTitle({ commit }, { conversationId, title }) {
      try {
        await api.put(`/chat/conversations/${conversationId}/title`, null, {
          params: { title },
        })
        commit('UPDATE_CONVERSATION_TITLE', { conversationId, title })
        return { success: true }
      } catch (error) {
        throw error
      }
    },
    // 直接更新store中的对话标题（不调用API）
    updateConversationTitleLocal({ commit }, { conversationId, title }) {
      commit('UPDATE_CONVERSATION_TITLE', { conversationId, title })
      return { success: true }
    },
    async sendMessage({ commit, state }, { conversationId, content }) {
      try {
        // 添加用户消息
        const userMessage = {
          id: Date.now(),
          role: 'user',
          content: content,
          createTime: new Date().toISOString(),
        }
        commit('ADD_MESSAGE', userMessage)

        // 发送消息到后端
        const response = await api.post('/chat/send', {
          conversationId,
          content,
        })

        // 添加AI回复
        const aiMessage = {
          id: response.data.messageId,
          role: 'assistant',
          content: response.data.content,
          createTime: new Date().toISOString(),
        }
        commit('ADD_MESSAGE', aiMessage)

        return response
      } catch (error) {
        throw error
      }
    },
  },
  modules: {},
})
